'use strict'
var express = require('express');
var router = express.Router();
const User = require('../models/models').user;
// const modelUtils = require('../utils/modelUtils');
const sms = require('../modules/lookup.1.js');
const md5 = require('md5');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const session = require('express-session');
const sess = session({
    cookie: 60 * 10000000,
    secret: '?ccmsshowsecrete?',
    resave: true,
    saveUninitialized: true
});
var path = require('path');
const isTest = true;

// GET route for reading data
router.get('/', function (req, res, next) {
    return res.sendFile(path.join(__dirname + '/templateLogReg/index.html'));
});


//POST route for updating data
router.post('/signup', function (req, res, next) {
    // confirm that user typed same password twice
    if (req.body.password !== req.body.passwordConf) {
        var err = new Error('Passwords do not match.');
        err.status = 400;
        res.send("passwords dont match");
        return next(err);
    }

    if (req.body.email &&
        req.body.username &&
        req.body.password &&
        req.body.passwordConf) {

        var userData = {
            email: req.body.email,
            username: req.body.username,
            password: req.body.password,
        }

        User.create(userData, function (error, user) {
            if (error) {
                return next(error);
            } else {
                req.session.userId = user._id;
                return res.redirect('/profile');
            }
        });

    } else if (req.body.logemail && req.body.logpassword) {
        User.authenticate(req.body.logemail, req.body.logpassword, function (error, user) {
            if (error || !user) {
                var err = new Error('Wrong email or password.');
                err.status = 401;
                return next(err);
            } else {
                req.session.userId = user._id;
                return res.redirect('/profile');
            }
        });
    } else {
        var err = new Error('All fields required.');
        err.status = 400;
        return next(err);
    }
})

function validateUserInfo(users, email, pwd) {
    for (let i in users) {
        let u = users[i];
        if (u.email === email && u.password === pwd)
            return true
    }
    return false;
}

function validatePhoneNumber(users, phoneNumber) {
    for (let i in users) {
        let u = users[i];
        if (u.phone === email)
            return true
    }
    return false;
}

function userExists(users, email) {
    for (let i in users) {
        let u = users[i];
        if (u.email === email)
            return true
    }
    return false;
}

/**
 * 根据body参数区分是哪一种操作
 */
router.post('/', (req, res) => {
    // User.findOne({email: 'admin@ectivisecloud.com'}).exec()
    //     .then(doc => {
    //         console.log(doc)
    //     }).catch(err => {
    //     console.log(err)
    // })
    // console.debug(req.body);
    // if(!req.body || !req.body.mobile || !req.body.password){
    //   res.json({
    //     errorCode: 0,
    //     message: '请输入正确的电话号码和密码.'
    //   });
    // }
    //判断是否已经注册过
    var logmobile = req.body.logmobile;
    // var countryCode = (req.body.countryCode) ? req.body.countryCode : '65';
    // var phoneNum = countryCode + mobile;
    var phoneNum = '91550473';
    var isLogin = logmobile && validatePhoneNumber(users);
    isLogin =   (req.body.email && req.body.password);

    if(logmobile){

    }
    else
    {
    }

    let rawdata = fs.readFileSync('users.json');
    let users = JSON.parse(rawdata);
    console.log(users);
    // let e = users.email, p = users.password;
    let isMatch = false;
    if(phoneNum){
        validatePhoneNumber(users, req.body.mobile);
    } else {
        validateUserInfo(users, req.body.logemail, req.body.logpassword);
    }
    // let e = u.email,p=u.password;

    if(isTest)
        return res.sendFile(path.join(__dirname, '/gponcal0313.html'))
    if (isLogin) {//&& req.body.logemail == 'admin@ectivisecloud.com' && req.body.logpassword === 'password'
        if (isMatch)
            return res.sendFile(path.join(__dirname, '/gponcal0313.html'))
        else
            return res.send("email or passwords dont match");
    } else {
        if (userExists(users, req.body.logemail)) {
            return res.send("user exists.")
        } else {
            if (req.body.password !== req.body.passwordConf) {
                return res.send("password not match.")
            }
            // let newUser = {
            //     email: req.body.email,
            //     password: req.body.password
            // }
            users.push({
                    email: req.body.email,
                    password: req.body.password
                }
            )
            fs.writeFileSync('users.json', JSON.stringify(users));
            return res.sendFile(path.join(__dirname, '/gponcal0313.html'))
        }
        // User.findOne({email: 'liqin@hotmail.sg'}).exec()
        //     .then(doc => {
        //         console.log(doc)
        //     }).catch(err => {
        //         console.log(err)
        //     })
        // res.send("passwords dont match");
        // return next(err);
        if (false) {
            User.findOne({
                email: req.body.email
            }, (err, user) => {
                if (err) {
                    throw err;
                }
                if (user) {
                    res.json({
                        errorCode: 2,
                        message: 'user exists'
                    });
                } else {
                    var token = jwt.sign({
                        email: req.body.email,
                    }, config.secret, {});
                    var newUser = new User({
                        email: req.body.email,
                        countryCode: '65',
                        mobile: phoneNum,
                        password: req.body.password,
                        token: token,
                        isEnabled: true,
                        roleType: 0
                    });
                    newUser.userCode = newUser._id;
                    //send 4 digits code.
                    var randCode = Math.floor(1000 + Math.random() * 9000);
                    console.debug('sms random code=%s', randCode);
                    var msg = 'OTP' + randCode + 'Please complete registration in 3 min';
                    if (false) sms.sendsms(phoneNum, msg, function (data) {
                    });
                    //setup the session for 2FA
                    var s = {
                        timestamp: Date.now() + 180000,
                        user: newUser,
                        verifyCode: randCode
                    };

                    var md5str = md5(token);
                    console.log(md5str);
                    console.log(md5(token));
                    sess[md5str] = s;

                    res.json({
                        errorCode: 1,
                        message: '4 digits code sent!',
                        data: {
                            token: token,
                            userCode: newUser._id
                        }
                    })
                }
            })
        }
    }
});

// GET route after registering
router.get('/profile', function (req, res, next) {
    // return res.sendFile(path + "/gponcal0313.html");
    return res.sendFile(path.join(__dirname + '/gponcal0313.html'));
    //return res.send('<h1>Name: </h1>' + user.username + '<h2>Mail: </h2>' + user.email + '<br><a type="button" href="/logout">Logout</a>')

    if (false) User.findById(req.session.userId)
        .exec(function (error, user) {
            if (error) {
                return next(error);
            } else {
                if (user === null) {
                    var err = new Error('Not authorized! Go back!');
                    err.status = 400;
                    return next(err);
                } else {
                    return res.send('<h1>Name: </h1>' + user.username + '<h2>Mail: </h2>' + user.email + '<br><a type="button" href="/logout">Logout</a>')
                }
            }
        });
});

// GET for logout logout
router.get('/logout', function (req, res, next) {
    if (req.session) {
        // delete session object
        req.session.destroy(function (err) {
            if (err) {
                return next(err);
            } else {
                return res.redirect('/');
            }
        });
    }
});

module.exports = router;

/**
 * simply send sms and return the random code for verification
 * @param phoneNum
 * @return {number}
 */
function send_SMS(phoneNum) {
    var randCode = Math.floor(1000 + Math.random() * 9000);
    console.debug('sms random code=%s', randCode);
    var msg = '【秀】您的验证码是' + randCode + '。如非本人操作，请忽略。请在60分钟之内完成验证操作';
    sms.sendsms(phoneNum, msg, function (data) {
    });
    return randCode
}
